package com.chuantou.yuba.ui.fragment;

import java.util.HashMap;
import java.util.List;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.chuantou.yuba.R;
import com.chuantou.yuba.adapter.IntegralAdapter;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.BaseGsonRequest;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.IntegralDataTO;
import com.chuantou.yuba.api.to.IntegralTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.ui.widget.LoadingView.Style;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.Constants;

public class IntegralListFragment extends PaginationListFragment<IntegralDataTO> {
	private IntegralAdapter mAdapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = super.onCreateView(inflater, container, savedInstanceState);
		if (mAdapter == null) {
			mAdapter = new IntegralAdapter(mContext);
			mListView.setHeaderDividersEnabled(true);
			mListView.addHeaderView(inflater.inflate(R.layout.integral_list_header, null));
			mListView.setAdapter(mAdapter);
			startRequest();
		}
		return view;
	}

	@Override
	protected BaseGsonRequest<IntegralDataTO> getRequest(Listener<IntegralDataTO> listener, ErrorListener errorListener) {
		String url = UriHelper.getIntegralListUrl();
		HashMap<String, String> params = new HashMap<String, String>();
		UserTO user = AccountManager.getInstance(mContext).getUserTO();
		params.put(UriHelper.PARAMS_UID, user != null ? String.valueOf(user.getUid()) : "0");
		params.put(UriHelper.PARAMS_TOKEN, user != null ? user.getToken() : "");
		params.put(UriHelper.PARAMS_PAGE_SIZE, String.valueOf(Constants.DEFAULT_PAGE_SIZE));
		params.put(UriHelper.PARAMS_PAGE_NO, String.valueOf(1));
		GsonRequest<IntegralDataTO> request = new GsonRequest<IntegralDataTO>(Method.POST, url, listener, errorListener, params, IntegralDataTO.class);
		return request;
	}

	@Override
	protected String getEmptyString() {
		return mContext.getString(R.string.no_integral_list);
	}

	@Override
	public void onResponse(IntegralDataTO response) {
		if (getActivity() != null) {
			super.onResponse(response);
			if (response != null) {
				List<IntegralTO> integrals = response.getIntegrals();
				// 第一页
				if (response.getCurrentPage() <= 1) {
					// 保存到本地数据库缓存
					mAdapter.clear();
				}
				mAdapter.add(integrals);
				mLoadingView.setStyle(Style.EMPTY, getEmptyString());
			} else {
				mLoadingView.setStyle(Style.EMPTY, getEmptyString());
			}
			mAdapter.notifyDataSetChanged();
		}
	}

}
